//
//  HELPersonSettingVC.m
//  HandheldELearn
//
//  Created by 陈武琦 on 16/7/11.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELPersonSettingVC.h"
#import "HELPersonSettingHeaderView.h"
#import "HELPersonSettingCell.h"
#import "HELUserInfoM.h"
#import "UIButton+WebCache.h"
#import "HELLoginVC.h"
#import "CustomAlertView.h"
#import "NSString+Utilities.h"
#import "UIViewController+BackButtonHandler.h"

static NSString *cellID = @"HELPersonSettingCellID";

@interface HELPersonSettingVC ()<UITableViewDataSource,UITableViewDelegate, HELPersonSettingHeaderViewDelegate, UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIAlertViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)HELPersonSettingHeaderView *tableHeadView;
@property(nonatomic, assign)BOOL isUpdateHeadPhoto;
@end

@implementation HELPersonSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _isUpdateHeadPhoto = NO;
    _userInfoModel = [HELUserInfoM new];
    [self titleView:@"个人设置"];
    self.view.backgroundColor = [UIColor  whiteColor];

    [self.tableView registerNib:[UINib nibWithNibName:@"HELPersonSettingCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellID];
    [self addTableHeadView];
    [self footerAddBtnWith:@"退出当前账号"];
    [self setNavToBlue];
    //筛选
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(save)];
    [self.navigationItem setRightBarButtonItem:saveItem];
    
    [self requestData];
    
}


- (void)addTableHeadView {
    
    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"HELPersonSettingHeaderView" owner:nil options:nil];
    _tableHeadView = [nibContents lastObject];
    _tableHeadView.delegate = self;
    _tableHeadView.bounds = CGRectMake(0, 0, kScreenWidth, 120);
    _tableHeadView.headPhoto.layer.cornerRadius = 30;
    _tableHeadView.headPhoto.layer.borderWidth = 1.0;
    _tableHeadView.headPhoto.layer.borderColor = [UIColor whiteColor].CGColor;
    _tableHeadView.headPhoto.layer.masksToBounds = YES;
    self.tableView.tableHeaderView = _tableHeadView;
}

- (void)requestData {

    /*
     *获取个人信息
     */
    HELUserInfoM *userInfo = [HELAppManager userInfo];
    if (!userInfo.userId) {
        alertMessage(@"用户id获取失败");
        return;
    }
    weakSelf_define;
    cwqHud(self.view);
    NSDictionary *param = @{@"userId":userInfo.userId};
    [[HELNetworkManager sharedMg] GET:helUserInfoUrl parameters:param success:^(id responseObject) {
        
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            HELUserInfoM *model = [HELUserInfoM mj_objectWithKeyValues:responseObject];
            weakSelf.userInfoModel = model;
            [weakSelf updateLocalUserInfo:model];
            
            [weakSelf.tableHeadView.headPhoto sd_setImageWithURL:[NSURL URLWithString:model.photoShowMap.mini] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"headPhoto"]];
            [weakSelf.tableView reloadData];
            cwqHudSuccess(hud);
        }
        
        
    } failure:^(NSString *err) {
        cwqHudRequestError(err);
        
    }];
}


/*
 *保存
 */
- (void)save {

   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否保存？" message:nil delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
    alert.tag = 101;
    [alert show];
    
}

- (void)updateLocalUserInfo:(HELUserInfoM *)newInfo {

    helUserInfo
    if (newInfo.photo && ![userInfo.photo isEqualToString:newInfo.photo]) {
        userInfo.photo = newInfo.photo;
        NSString *baseURL = [[[HELNetworkManager sharedMg] getBaseUrl] stringByAppendingString:@"/upload/userphoto/"];
        userInfo.photoShowMap = newInfo.photoShowMap;
        userInfo.photoShowMap.mini = [baseURL stringByAppendingString:newInfo.photo];
    }
    if (newInfo.email && ![userInfo.email isEqualToString:newInfo.email]) {
        
        userInfo.email = newInfo.email;
    }
    
    NSMutableDictionary *dict = [[userInfo mj_keyValues] mutableCopy];
    [HELAppManager saveUseInfo:dict];

}

#pragma mark - ----------------uialertViewDelegate--------------------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        switch (alertView.tag) {
            case 101:
                if (self.isUpdateHeadPhoto) {//修改了头像
                    [self uploadHeadPhoto:self.tableHeadView.headPhoto.imageView.image];
                }else {
                    //没修改头像
                    HELUserInfoM *userInfo = [HELAppManager userInfo];
                    if ([self.userInfoModel.email isEqualToString:userInfo.email] || !self.userInfoModel.email) {
                        cwqAlertMessage(@"请修改后再保存~");
                        return;
                    }
                    [self updateUserInfo];
                }
                break;
                
            case 102:{
        //退出登录
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"login"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                HELLoginVC *loginVC = [HELLoginVC new];
                HELNavigationContrller *nav = [[HELNavigationContrller alloc] initWithRootViewController:loginVC];
                [nav resetNav];
                [self presentViewController:nav animated:YES completion:nil];
            }
                break;
                
            case 1001:{
                //返回提示
                [self.navigationController popViewControllerAnimated:YES];
                
                }
                
                break;
            default:
                break;
        }
    }
}



/*
 *上传头像
 */
- (void)uploadHeadPhoto:(UIImage *)image{
    
    helUserInfo
    weakSelf_define;
    cwqHud(self.view);
    NSDictionary *param = @{@"userId":userInfo.userId};
    
    [[HELNetworkManager sharedMg] UPLOAD:helUploadHeadPhotofoUrl parameters:param image:image progress:^(CGFloat percent) {
        
    } success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            weakSelf.userInfoModel.photo = responseObject[@"root"];
            [weakSelf updateUserInfo];
        }
    } failure:^(NSString *err) {
        cwqHudRequestError(err);
    }];
    
}

/*
 *修改个人信息
 */

- (void)updateUserInfo {
   __block HELUserInfoM *userInfo = [HELAppManager userInfo];
    if (!userInfo.userId) {
        alertMessage(@"用户id获取失败");
        return;
    }
    weakSelf_define;
    cwqHud(self.view);
    
    NSMutableDictionary *param = [@{@"userId":userInfo.userId} mutableCopy];
    if (self.userInfoModel.email) {
        [param setObject:self.userInfoModel.email forKey:@"email"];
    }
    ;
    if (self.isUpdateHeadPhoto && self.userInfoModel.photo) {
        [param setObject:self.userInfoModel.photo forKey:@"photo"];
    }
    [[HELNetworkManager sharedMg] GET:helUpdateUserInfoUrl parameters:param success:^(id responseObject) {
        
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            alertMessage(@"保存成功");
        [weakSelf updateLocalUserInfo:weakSelf.userInfoModel];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        
    } failure:^(NSString *err) {
        cwqHudRequestError(err);
        
    }];

}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}


- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 64) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = kAppBg;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_tableView];
    }
    return  _tableView;
}


- (void)footerAddBtnWith:(NSString *)title{
    
    UIButton *footerBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    footerBtn.frame =CGRectMake(15, kScreenHeight - 64 - 64, kScreenWidth -30, 40);
    [footerBtn setTitle:title forState:UIControlStateNormal];
    [footerBtn setBackgroundColor:kBtnColor];
    footerBtn.layer.cornerRadius = 5;
    footerBtn.layer.masksToBounds= YES;
    footerBtn.tag = 900;
    [footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [footerBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:footerBtn];
}
- (void)logout {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否退出？" message:nil delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
    alert.tag = 102;
    [alert show];

}


#pragma mark - <UITableViewData and UITableDelegate>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 6;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 44;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HELPersonSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    switch (indexPath.row) {
        case 0:{
        cell.title.text = @"手机号";
        cell.titleContent.text = self.userInfoModel.mobilephone;
        cell.rightIcon.hidden = YES;
        }
            
            break;
        case 1:{
            cell.title.text = @"所属科室";
            cell.titleContent.text = self.userInfoModel.departmentName;
            cell.rightIcon.hidden = YES;
        }
            
            break;
        case 2:{
            cell.title.text = @"真实姓名";
            cell.titleContent.text = self.userInfoModel.trueName;
            cell.rightIcon.hidden = YES;
        }
            
            break;
        case 3:{
            cell.title.text = @"成员编号";
            cell.titleContent.text = self.userInfoModel.jobNum;
            cell.rightIcon.hidden = YES;
        }
            
            break;
        case 4:{
            cell.title.text = @"性别";
            if ([self.userInfoModel.sex integerValue] == 1) {
                
                cell.titleContent.text = @"男";
            }else {
                cell.titleContent.text = @"女";
            
            }
            cell.rightIcon.hidden = YES;
        }
            
            break;
        case 5:{
            cell.title.text = @"电子邮箱";
            cell.titleContent.text = self.userInfoModel.email;
//            cell.rightIcon.hidden = YES;
        }
  
            break;
            
        default:
            break;
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 5) {
        weakSelf_define;
        CustomAlertView *alert = [[CustomAlertView alloc] initWithAlertViewHeight:248];
        alert.titleLabel.text = @"请输入邮箱";
        alert.textField.placeholder = @"请输入邮箱号...";
        alert.ButtonClick = ^void(NSString *text){
            weakSelf.userInfoModel.email = text;
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            
        };
    }

}


#pragma mark -------------headPhotoClick--------------------
- (void)headPhotoClick {

    UIActionSheet *actionSheetView = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册" ,nil];
    [actionSheetView showInView:self.navigationController.view];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 0) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera ]) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else if(buttonIndex == 1){
    
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
    
    }

}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    [self.tableHeadView.headPhoto setImage:img forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.isUpdateHeadPhoto = YES;
}

-(BOOL) navigationShouldPopOnBackButton ///在这个方法里写返回按钮的事件处理
{
    HELUserInfoM *userInfo = [HELAppManager userInfo];
    //如果用户修改了内容
   if (self.isUpdateHeadPhoto || (![self.userInfoModel.email isEqualToString:userInfo.email] && self.userInfoModel.email)) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否放弃修改？" message:nil delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alert.tag = 1001;
        [alert show];
        return NO;
    }
    [self.navigationController popViewControllerAnimated:YES];
    return YES;//返回NO 不会执行
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
